/**
 * Created by leiweibo on 6/28/15.
 */

var app = angular.module('mainservice', []);

app.factory('Main', function($http, $localStorage, $q, $filter, $timeout, BaseService) {
  function changeUser(user) {
    angular.extend(currentUser, user);
  }

  function urlBase64Decode(str) {
    var output = str.replace('-', '+').replace('_', '/');
    switch (output.length % 4) {
      case 0:
        break;
      case 2:
        output += '==';
        break;
      case 3:
        output += '=';
        break;
      default:
        throw 'Illegal base64url string!';
    }
    return window.atob(output);
  }

  function getUserFromToken() {
    var token = $localStorage.token;
    var user = {};

    if (typeof token !== 'undefined') {
      var encoded = token.split('.')[1];
      user = JSON.parse(urlBase64Decode(encoded));
    }
    return user;
  }

  var currentUser = getUserFromToken();

  function getPage(pageNo, pageSize, params, success) {

    var filterCondition = params.search.predicateObject;
    var queryStr = '';
    if (filterCondition) {
      if (filterCondition.username) {
        queryStr += ('&username=' + filterCondition.username);
      }

      if (filterCondition.realname) {
        queryStr += ('&realname=' + filterCondition.realname);
      }
    }
    $http.get(BaseService.baseUrl + "/user/list?pageNo=" + pageNo + "&pageSize=" + pageSize + queryStr)
      .success(success);
  }

  return {
    signin: function(data, success, error) {
      $http.post(BaseService.baseUrl + "/user/signin", data).success(success).error(error);
    },
    me: function(success, error) {
      $http.get(BaseService.baseUrl + '/user/me').success(success).error(error)
    },
    logout: function(success) {
      $http.get(BaseService.baseUrl + '/user/logout').success(success);
    },
    getPage: getPage,
    createUser: function(data, success, error) {
      $http.post(BaseService.baseUrl + '/user/create', data).success(success).error(error);
    },
    updateUser: function(data, success, error) {
      $http.put(BaseService.baseUrl + '/user/update', data).success(success).error(error);
    },
    deleteUser: function(data, success, error) {
      $http.delete(BaseService.baseUrl + '/user/delete?id=' + data.id).success(success).error(error);
    }
  }
}).factory('UserData', function() {
  var savedUserData = {};
  function set(data) {
    savedUserData = data;
  }
  function get() {
    return savedUserData;
  }

  return {
    set: set,
    get: get
  }
});

